package com.example.pt.repository;

import com.example.pt.entity.Torrent;
import jakarta.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.awt.print.Pageable;
import java.util.List;
import java.util.Optional;

@Repository
public interface TorrentRepository extends JpaRepository<Torrent, String> {

    @Query(value = "SELECT * FROM torrent t WHERE t.category = :category ORDER BY t.uploaded_at DESC LIMIT :limit",
            nativeQuery = true)
    List<Torrent> findRecommendedByCategory(@Param("category") String category, @Param("limit") int limit);

    @Query(value = "SELECT * FROM torrent ORDER BY download_count DESC LIMIT :limit",
            nativeQuery = true)
    List<Torrent> findTopDownloaded(@Param("limit") int limit);


    @Query(value = "SELECT * FROM torrent ORDER BY download_count DESC LIMIT 5", nativeQuery = true)
    List<Torrent> findTop5ByDownloadCount();

    @Query(nativeQuery = true,
            value = "SELECT * FROM torrent ORDER BY download_count ASC LIMIT 5")
    List<Torrent> findTop5ByLowestDownloadCount();

    // 按名字模糊搜索（忽略大小写）
    List<Torrent> findByNameContainingIgnoreCase(String name);

    @Query(value = "SELECT * FROM torrent ORDER BY RAND() LIMIT :limit", nativeQuery = true)
    List<Torrent> findRandomTorrents(@Param("limit") int limit);

    Optional<Torrent> findById(String infoHash);

    @Query("SELECT t FROM Torrent t WHERE t.infoHash = :infoHash")
    Optional<Torrent> findByInfoHash(String infoHash);


    @Query("SELECT t FROM Torrent t WHERE t.id = :id")
    Optional<Torrent> findByTorrentId(Long id);
    List<Torrent> findByUploaderId(Long uploaderId);

    @Modifying
    @Transactional
    @Query("delete from Torrent t where t.id = :id")
    int deleteByIdValue(@Param("id") Long id);

    Optional<Torrent> findById(Long id);

}
